package com.hwadee.property.controller.people;

import com.hwadee.property.pojo.User;
import com.hwadee.property.dto.UserStatistics;
import com.hwadee.property.service.ICommunityService;
import com.hwadee.property.service.IUserService;
import com.hwadee.property.util.AjaxResult;
import com.hwadee.property.util.JwtUtil;
import com.hwadee.property.dto.PageResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@Api(tags = "用户-UserController", description = "用户相关接口")
@CrossOrigin
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    @ApiOperation(value = "【用户】登录", notes = "用于用户登录,登录成功在data中返回当前用户id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "用户名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
    })
    public AjaxResult login(
            @RequestParam(value = "account") String account,
            @RequestParam(value = "password") String password) {
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        User bean = userService.doLogin(user);
        if (bean != null) {
            String token = jwtUtil.generateToken(bean.getId(), bean.getUserType());
            AjaxResult result = AjaxResult.success(bean.getId());
            result.put("token", token);
            return result;
        }
        return AjaxResult.fail();
    }

    @GetMapping("/personal")
    @ApiOperation(value = "【用户】查询个人信息", notes = "获取用户的个人信息")
    public AjaxResult getPersonalInfo(@RequestHeader(value = "Authorization", required = false) String token) {
        if (StringUtils.isEmpty(token)) {
            return AjaxResult.fail("未授权, token 为空");
        }

        token = token.replaceFirst("(?i)Bearer ", ""); // 兼容大小写的 "Bearer "

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据用户ID查询用户信息
            User user = userService.getById(userId);

            if (user == null) {
                return AjaxResult.fail("用户不存在");
            }

            return AjaxResult.success(user);
        } catch (Exception e) {
            return AjaxResult.error("获取个人信息失败:" + e.getMessage());
        }
    }

    @GetMapping("/userStatistics")
    @ApiOperation(value = "【管理员】获取某一个小区的用户统计数据", notes = "根据小区id获取用户统计数据，可以得到小区名称、小区的用户数量、小区的业主数量、小区的物业数量以及所有用户的具体信息")
    public AjaxResult getUserStatistics(@RequestHeader("Authorization") String token, @RequestParam Long communityId){
        if (StringUtils.isEmpty(token)) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 根据小区ID获取小区名称
            String communityName = communityService.getById(communityId).getCommunityName();
            if (communityName == null) {
                return AjaxResult.fail("小区不存在");
            }

            // 获取小区的用户数量
            int totalUserCount = userService.getUserCountByCommunityId(communityId);

            // 获取小区的业主数量（用户类型为1）
            int ownerCount = userService.getUserCountByCommunityIdAndUserType(communityId, 1);

            // 获取小区的物业数量（用户类型为2）
            int propertyCount = userService.getUserCountByCommunityIdAndUserType(communityId, 2);

            // 获取小区内所有用户的具体信息
            List<User> users = userService.listByCommunityId(communityId);

            // 构建返回的统计数据
            UserStatistics statistics = new UserStatistics();
            statistics.setCommunityId(communityId);
            statistics.setCommunityName(communityName);
            statistics.setTotalUserCount(totalUserCount);
            statistics.setOwnerCount(ownerCount);
            statistics.setPropertyCount(propertyCount);
            statistics.setUsers(users);

            return AjaxResult.success(statistics);
        } catch (Exception e) {
            return AjaxResult.error("获取用户统计数据失败: " + e.getMessage());
        }
    }

    @PutMapping("/personalUpdate")
    @ApiOperation(value = "【用户】修改个人信息", notes = "修改用户的个人信息")
    public AjaxResult updatePersonalInfo(@RequestHeader(value = "Authorization") String token,
                                         @RequestParam(required = false) String name,
                                         @RequestParam(required = false) String account,
                                         @RequestParam(required = false) String password,
                                         @RequestParam(required = false) String sex,
                                         @RequestParam(required = false) Integer age,
                                         @RequestParam(required = false) String identification,
                                         @RequestParam(required = false) String phone,
                                         @RequestParam(required = false) String email) {
        // 如果token为空，返回错误
        if (StringUtils.isEmpty(token)) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据用户ID查询用户信息
            User user = userService.getById(userId);

            // 如果用户不存在，返回失败
            if (user == null) {
                return AjaxResult.fail("用户不存在");
            }

            // 调用修改方法，修改用户信息
            return updateUser(token, userId, name, account, password, sex, age, identification, phone, email);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.error("修改个人信息失败: " + e.getMessage());
        }
    }

    @GetMapping
    @ApiOperation(value = "【管理员】查询所有用户", notes = "获取系统中所有用户的信息")
    public AjaxResult getAllUsers() {
        List<User> users = userService.list();
        return AjaxResult.success(users);
    }

    @GetMapping("/property/page")
    @ApiOperation(value = "【物业】分页查询业主信息", notes = "根据条件分页查询物业权限范围内的业主信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页大小", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "account", value = "账号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "identification", value = "身份证号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "age", value = "年龄", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "用户类别", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "freeze", value = "冻结状态", dataType = "Integer", paramType = "query")
    })
    public AjaxResult getPage(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @ApiParam(value = "姓名") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "账号") @RequestParam(value = "account", required = false) String account,
            @ApiParam(value = "身份证号") @RequestParam(value = "identification", required = false) String identification,
            @ApiParam(value = "电话") @RequestParam(value = "phone", required = false) String phone,
            @ApiParam(value = "邮箱") @RequestParam(value = "email", required = false) String email,
            @ApiParam(value = "性别") @RequestParam(value = "sex", required = false) String sex,
            @ApiParam(value = "年龄")  @RequestParam(value = "age", required = false) Integer age,
            @ApiParam(value = "用户类别") @RequestParam(value = "userType", required = false) Integer userType,
            @RequestParam(value = "freeze", required = false) Integer freeze) {
        // 如果token为空，返回错误
        if (StringUtils.isEmpty(token)) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从token中解析出用户ID
            Long userId = jwtUtil.getUserId(token);

            // 根据用户ID查询用户信息
            User user = userService.getById(userId);

            // 如果用户不存在，返回失败
            if (user == null) {
                return AjaxResult.fail("用户不存在");
            }

            Long communityId = user.getCommunityId();

            // 调用getPage方法，分页查询信息
            return getPage(token, current, size, name, account, identification, phone, email, sex, age, communityId, userType,freeze);
        } catch (Exception e) {
            // token解析异常或其他异常，返回失败
            return AjaxResult.fail("查询业主信息失败");
        }
    }

    @GetMapping("/page")
    @ApiOperation(value = "【管理员】分页查询用户", notes = "根据条件分页查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页大小", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "account", value = "账号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "identification", value = "身份证号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "age", value = "年龄", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "communityId", value = "小区id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "用户类别", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "freeze", value = "冻结状态", dataType = "Integer", paramType = "query")
    })
    public AjaxResult getPage(@RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @ApiParam(value = "姓名") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "账号") @RequestParam(value = "account", required = false) String account,
            @ApiParam(value = "身份证号") @RequestParam(value = "identification", required = false) String identification,
            @ApiParam(value = "电话") @RequestParam(value = "phone", required = false) String phone,
            @ApiParam(value = "邮箱") @RequestParam(value = "email", required = false) String email,
            @ApiParam(value = "性别") @RequestParam(value = "sex", required = false) String sex,
            @ApiParam(value = "年龄")  @RequestParam(value = "age", required = false) Integer age,
            @ApiParam(value = "小区id") @RequestParam(value = "communityId", required = false) Long communityId,
            @ApiParam(value = "用户类别") @RequestParam(value = "userType", required = false) Integer userType,
            @RequestParam(value = "freeze", required = false) Integer freeze) {

        PageResult<User> pageResult = userService.getPage(current, size, name, account, identification, phone, email, sex, age, communityId, userType, freeze);
        return AjaxResult.success(pageResult);
    }

    @GetMapping("/type/{userType}")
    @ApiOperation(value = "【管理员】根据用户类型查询用户", notes = "根据用户类型（1-业主，2-物业）查询用户")
    @ApiImplicitParam(name = "userType", value = "用户类型（1-业主，2-物业）", required = true, dataType = "Integer", paramType = "path")
    public AjaxResult getUsersByType(@RequestHeader("Authorization") String token, @PathVariable Integer userType) {
        List<User> users = userService.listByUserType(userType);
        return AjaxResult.success(users);
    }

    @GetMapping("/community/{communityId}")
    @ApiOperation(value = "【管理员】根据小区 ID 查询用户", notes = "根据小区 ID 查询用户")
    @ApiImplicitParam(name = "communityId", value = "小区 ID", required = true, dataType = "Long", paramType = "path")
    public AjaxResult getUsersByCommunityId(@RequestHeader("Authorization") String token, @PathVariable Long communityId) {
        List<User> users = userService.listByCommunityId(communityId);
        return AjaxResult.success(users);
    }

    @GetMapping("/phone/{phone}")
    @ApiOperation(value = "【管理员】根据手机号码查询用户", notes = "根据手机号码查询用户")
    @ApiImplicitParam(name = "phone", value = "手机号码", required = true, dataType = "String", paramType = "path")
    public AjaxResult getUserByPhone(@RequestHeader("Authorization") String token, @PathVariable String phone) {
        User user = userService.getByPhone(phone);
        if (user == null) {
            return AjaxResult.fail("用户不存在");
        }
        return AjaxResult.success(user);
    }

    @PostMapping("/register")
    @ApiOperation(value = "【管理员】注册新用户", notes = "注册新用户，需要提供用户的基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "age", value = "年龄", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "identification", value = "身份证号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "电话", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "communityId", value = "小区id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "userType", value = "用户类别", required = true, dataType = "Integer", paramType = "query")
    })
    public AjaxResult registerUser(
            @ApiParam(value = "姓名") @RequestParam String name,
            @ApiParam(value = "账号") @RequestParam String account,
            @ApiParam(value = "密码") @RequestParam String password,
            @ApiParam(value = "性别") @RequestParam(required = false) String sex,
            @ApiParam(value = "年龄") @RequestParam(required = false) Integer age,
            @ApiParam(value = "身份证号") @RequestParam String identification,
            @ApiParam(value = "电话") @RequestParam String phone,
            @ApiParam(value = "邮箱") @RequestParam String email,
            @ApiParam(value = "小区id") @RequestParam Long communityId,
            @ApiParam(value = "用户类别") @RequestParam Integer userType) {
        User user = new User();
        user.setName(name);
        user.setAccount(account);
        user.setPassword(password);
        if (StringUtils.hasText(sex)) {
            user.setSex(sex);
        }
        if (age != null) {
            user.setAge(age);
        }
        user.setIdentification(identification);
        user.setPhone(phone);
        user.setEmail(email);
        user.setCommunityId(communityId);
        user.setUserType(userType);
        boolean success = userService.registerUser(user);
        if (success) {
            return AjaxResult.success("用户注册成功");
        } else {
            return AjaxResult.fail("用户注册失败");
        }
    }

    @PutMapping("/updateUser")
    @ApiOperation(value = "【管理员】更新用户信息", notes = "更新用户信息，需要提供用户 ID 和更新后的信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "account", value = "账号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "age", value = "年龄", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "identification", value = "身份证号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱", dataType = "String", paramType = "query")
    })
    public AjaxResult updateUser(@RequestHeader("Authorization") String token,
                                 @RequestParam Long id,
                                 @RequestParam(required = false) String name,
                                 @RequestParam(required = false) String account,
                                 @RequestParam(required = false) String password,
                                 @RequestParam(required = false) String sex,
                                 @RequestParam(required = false) Integer age,
                                 @RequestParam(required = false) String identification,
                                 @RequestParam(required = false) String phone,
                                 @RequestParam(required = false) String email) {
        User user = userService.getById(id);
        if (user == null) {
            return AjaxResult.fail("用户不存在");
        }
        user.setName(name);
        user.setAccount(account);
        user.setPassword(password);
        if (sex != null) user.setSex(sex);
        if (age != null) user.setAge(age);
        if (identification != null) user.setIdentification(identification);
        if (phone != null) user.setPhone(phone);
        if (email != null) user.setEmail(email);
        boolean updated = userService.updateById(user);
        return updated ? AjaxResult.success("用户更新成功") : AjaxResult.fail("用户更新失败");
    }

    @PutMapping("/freeze/{id}")
    @ApiOperation(value = "【物业/管理员】冻结用户", notes = "根据用户 ID 冻结用户")
    @ApiImplicitParam(name = "id", value = "用户 ID", required = true, dataType = "Long", paramType = "path")
    public AjaxResult freezeUser(@PathVariable Long id) {
        User user = new User();
        user.setId(id);
        user.setFreeze(1);
        boolean success = userService.updateUser(user);
        if (success) {
            return AjaxResult.success("用户账户冻结成功");
        } else {
            return AjaxResult.fail("冻结失败");
        }
    }
}
